// pages/diary/diary.js
const db = wx.cloud.database();
const app = getApp();
const fs = wx.getFileSystemManager();
const httpUrl = "https://6d61-manbu-2ggvwdnk1d8bd0fa-1316354189.tcb.qcloud.la/";
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0';
var today = new Date();
var year = today.getFullYear();
var month = today.getMonth() + 1;
var day = today.getDate();
var loading = true;
var emoji = "愉悦";
var id = "";
var openid = "";
var authorid = "";
var emojiScore = 5;
var diary = "";
var sentence = "";
var pic = "";
var likeit = false;
var favouriteit = false;
var imageList = [];
var localImageList = [];
var cloudImageList = [];
var cloudImageDict = {};
var fixmode = false;
var hasFixed = false;
var createTime = new Date();
var authorNickname = "";
var authorAvatar = "";
var authorSignature = "";
var selectComment = "";
var commentAuthorNickname = "";
var emojiArray = [
    {score: 5,text:"愉悦",selected:true,src:"../../images/laughing.png"},
    {score: 4,text:"轻松",selected:false,src:"../../images/smile.png"},
    {score: 3,text:"无语",selected:false,src:"../../images/sighing.png"},
    {score: 2,text:"发愁",selected:false,src:"../../images/crying.png"},
    {score: 1,text:"崩溃",selected:false,src:"../../images/angry.png"}];
var themeColor = "#FAE2C0";
var deepThemeColor = "#FFA638";
var publish = false;
var visit = false;
var commentText = "";
var commentList = []
Page({

    /**
     * 页面的初始数据
     */
    data: {
        emojiArray: emojiArray,
        themeColor: themeColor,
        deepThemeColor: deepThemeColor,
        fixmode: fixmode,
        publish: false,
        isSelectComment: false,
        likeNumber: 0,
        favouriteNumber: 0
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.setThemeColor("愉悦");
        const eventChannel = this.getOpenerEventChannel()
        let that = this;
        cloudImageList = [];
        imageList = [];
        likeit = false;
        favouriteit = false;
        // 监听 acceptDataFromOpenerPage 事件，获取上一页面通过 eventChannel 传送到当前页面的数据
        eventChannel.on('acceptDataFromOpenerPage', function(data) {
            year = data.year;
            month = data.month;
            day = data.day;
            emoji = data.emoji;
            id = data.id;
            authorid = data.authorid;
            fixmode = data.fixmode;
            publish = data.publish;
            visit = data.visit;
            imageList = data.images;
            createTime = new Date(data.timeString);
            console.log(data.timeString);
            that.setData({
                fixmode: fixmode,
                visit: visit,
                publish: publish,
                createTime: createTime.toDateString()
            });
            // 自己的头像
            db.collection("infoDB").where({
                _openid: app.globalData.openid
            }).get({
                success: function(res) {
                    if ( res.data[0] ) {
                        let avatar = that.loadAvatar(res.data[0].avatar);
                        that.setData({
                            myAvatar: avatar
                        });
                    }
                }
            });

            if ( emoji != null ) {
                that.setThemeColor(emoji);
                let selectionDict = {"崩溃":1,"发愁":2,"无语":3,"轻松":4,"愉悦":5};
                that.selectionMove(5-selectionDict[emoji]);
            }
            if ( data.images == null )
                imageList = [];
            else
                imageList = data.images;
            if ( data.cloudimage == null )
                cloudImageDict = {};
            else {
                cloudImageDict = {};
                for ( let i in data.cloudimage ) {
                    if ( typeof data.cloudimage[i] == "object" ) {
                        let imageName = Object.values(data.cloudimage[i])[0];
                        cloudImageDict[i + ".jpg"] = imageName;
                    }
                    else if ( typeof data.cloudimage[i] == "string" ) {
                        cloudImageDict[i] = data.cloudimage[i];
                    }
                }
            }
            
            
            for(let i = 0; i <= 4; i++){
                emojiArray[i].selected = false
            }
            switch(emoji) {
                case "愉悦":emojiArray[0].selected = true;break;
                case "轻松":emojiArray[1].selected = true;break;
                case "无语":emojiArray[2].selected = true;break;
                case "发愁":emojiArray[3].selected = true;break;
                case "崩溃":emojiArray[4].selected = true;break;
            }
            diary = data.diary;
            if ( data.sentence != null )
                diary = data.sentence;
            if ( data.pic != null ) {
                imageList.push(data.pic);
            }

            db.collection("infoDB").where({
                _openid: authorid
            }).get({
                success: function(res) {
                    if ( res.data[0] ) {
                        authorNickname = res.data[0].nickname;
                        authorAvatar = that.loadAvatar(res.data[0].avatar);
                        authorSignature = res.data[0].signature;
                    } else {
                        authorNickname = "微信用户";
                        authorAvatar = defaultAvatarUrl;
                        authorSignature = "无";
                    }
                    
                    that.setData({
                        authorNickname,
                        authorAvatar,
                        authorSignature
                    });
                }
                
            });

            if ( id ) {
                that.getComment();
            }
            that.setData({
                year: year,
                month: month,
                day: day,
                emoji:emoji,
                diary:diary,
                id:id,
                diaryText: diary,
                emojiArray: emojiArray,
                imageList: imageList
            });
        });
    },
    loadAvatar(url){
        let file = url.substr(70,url.length);
        return httpUrl + file;
    },
    getComment(){
        let that = this;
        db.collection("diaryDB").doc(id).get({
            success: function(res) {
                commentList = res.data.comment;
                for ( let i in commentList ) {
                    commentList[i]["canDelete"] = app.globalData.openid == authorid || commentList[i]['openid'] == app.globalData.openid;
                    if ( commentList[i]["like"] ) {
                        commentList[i]["likeNumber"] = Object.keys(commentList[i]["like"]).length;
                        if ( app.globalData.openid in commentList[i]["like"] ) 
                            commentList[i]["likeit"] = true;
                        else 
                            commentList[i]["likeit"] = false;
                    }
                    else {
                        commentList[i]["likeNumber"] = 0;
                    }
                        
                    db.collection("infoDB").where({
                        _openid: commentList[i]['openid']
                    }).get({
                        success: function(res) {
                            if ( res.data.length == 0 ) {
                                commentList[i]["nickname"] = "微信用户";
                                commentList[i]["avatar"] = defaultAvatarUrl;
                            }
                            else {
                                commentList[i]["nickname"] = res.data[0].nickname;
                                commentList[i]["avatar"] = that.loadAvatar(res.data[0].avatar);
                            }
                            that.setData({
                                commentList
                            });
                        }
                    });
                }
                
                let like = res.data.like;
                let likeNumber = Object.keys(like).length;
                let favourite = res.data.favourite
                let favouriteNumber = Object.keys(favourite).length;
                if ( app.globalData.openid in like ) {
                    likeit = true;
                }
                if ( app.globalData.openid in favourite ) {
                    favouriteit = true;
                }


                that.setData({
                    commentList: commentList,
                    likeNumber: likeNumber,
                    likeit: likeit,
                    favouriteNumber: favouriteNumber,
                    favouriteit: favouriteit
                })
            }
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        if (typeof this.getTabBar === 'function' && this.getTabBar()) {
            this.getTabBar().setData({
                selected: 1
            })
        }
    },
    setThemeColor(color){
        let themeColorArr = {
            "愉悦": "#FAE2C0",
            "轻松": "#FDF3C0",
            "无语": "#D5ECD0",
            "发愁": "#D9D9F0",
            "崩溃": "#BCC9CF",
            "": "#FFFFFF"
        };
        let deepThemeColorArr = {
            "愉悦": "#FFA638",
            "轻松": "#FBEE69",
            "无语": "#ADDB89",
            "发愁": "#9AA8CB",
            "崩溃": "#373526",
            "": "#FFFFFF"
        }
        themeColor = themeColorArr[color];
        deepThemeColor = deepThemeColorArr[color];
        wx.setNavigationBarColor({
            frontColor: "#000000",
            backgroundColor: themeColor,
            animation: {
              duration: 0,
              timingFunc: 'easeIn'
            }
          })
        this.setData({
            themeColor: themeColor,
            deepThemeColor: deepThemeColor
        });
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.setData({
            replyTarget: null,
            replyPrefix: ""
        })
    },
    getText(e){
        diary = e.detail.value;
    },
    openWarning(){
        hasFixed = true;
        wx.enableAlertBeforeUnload({
            message: '您还未保存信息，是否退出当前页面？',
            success: function() {
            },
        })
    },
    emojiTap(e){
        let selectedScore = e.currentTarget.dataset.score
        emojiScore = selectedScore;
        let colorTextArr = ["","崩溃","发愁","无语","轻松","愉悦"];
        emoji = colorTextArr[emojiScore];
        this.setThemeColor(colorTextArr[emojiScore]);
        let i = 0
        for(i = 0; i <= 4; i++){
            emojiArray[i].selected = false
        }
        emojiArray[5-selectedScore].selected = true
        this.selectionMove(5-selectedScore);
        this.setData({
            emojiArray:emojiArray
        })
    },
    addDiary(){
        let that = this;
        wx.disableAlertBeforeUnload();
        if ( diary == "" ){
            wx.showToast({
                title: '没有记录日记！',
                icon: "error"
              })
        }
        else if ( emojiScore == 0 ){
            wx.showToast({
                title: '没有记录心情！',
                icon: "error"
              })
        }
        else {
            console.log(emoji);
            if ( id ) {
                db.collection("diaryDB").where({
                    _id: id,
                }).update({
                    data: {
                        emoji: emoji,
                        diary: diary,
                        cloudPath: db.command.set(cloudImageDict),
                        publish: publish,
                        createTime: db.serverDate()
                    }
                });
            }
            else {
                db.collection("diaryDB").add({
                    data: {
                        year: year,
                        month: month,
                        day: day,
                        emoji: emoji,
                        diary: diary,
                        cloudPath: cloudImageDict,
                        publish: publish,
                        createTime: db.serverDate(),
                        comment: [],
                        hot: 0,
                        like: {},
                        favourite: {}
                    }
                });
            }
            wx.navigateBack({
              delta: 0,
            })
        }
    },
    deleteDiary(){
        if ( id ) {
            wx.showModal({
                title: '真的要删除这篇日记？',
                content: '这可是满满的回忆哇！',
                cancelColor: '#6B7CA1',
                confirmColor: 'red',
                confirmText: '删除',
                success(res){
                    if(res.confirm){
                        db.collection("diaryDB").where({
                            _id: id,
                        }).remove();
                        wx.navigateBack({
                            delta: 0,
                        })
                    }
                }
            });
        }
        else {
            wx.showToast({
              title: '没有日记可删除！',
              icon: "error"
            })
            this.deleteError();
        }
    },
    addImage(){
        let that = this;
        wx.chooseMedia({
            camera: 'back',
            mediaType: 'image',
            sourceType: ['album', 'camera'],
            success(res){
                for ( let i in res.tempFiles ){
                    let localPath = res.tempFiles[i].tempFilePath;
                    imageList.push(localPath);
                    let imageName = localPath.substr(13,localPath.length+1);
                    let cloudPath = authorid + "/" + imageName;
                    wx.showLoading({
                      title: '上传图片至云服务器中',
                    })
                    wx.cloud.uploadFile({
                        filePath: localPath,
                        cloudPath: cloudPath,
                        success: (res) => {
                            cloudImageDict[imageName] = res.fileID;                
                            wx.hideLoading();
                        },
                        fail: (res) => {
                            console.log(res);
                        }
                    }); 
                }
                that.setData({
                    imageList: imageList
                });
            }
        })
        
    },
    lookImage(e){
        let current = imageList[e.currentTarget.dataset.idx];
        wx.previewImage({
            urls: imageList,
            current: current
        })
    },
    deleteImage(e){
        let current = e.currentTarget.dataset.idx;
        let that = this;
        wx.showModal({
            title: '真的要删除这张照片？',
            content: '这可是满满的回忆哇！',
            cancelColor: '#6B7CA1',
            confirmColor: 'red',
            confirmText: '删除',
            success(res){
                if(res.confirm){
                    let imageName = imageList[current].substr(91,imageList[current].length+1);
                    console.log(imageName);
                    imageList.splice(current,1);
                    let deleteList = [];
                    deleteList.push(cloudImageDict[imageName])
                    console.log(cloudImageDict[imageName]);
                    delete cloudImageDict[imageName];
                    
                    wx.cloud.deleteFile({
                        fileList: deleteList
                    })
                    that.setData({
                        imageList: imageList
                    });
                }
            }
        });
    },
    selectionMove(x){
        let animation = wx.createAnimation({
            duration: 500,
            timingFunction: 'ease',
        });
        let move = (25 + x*140) + "rpx"
        animation.left(move).step()
        this.setData({
            ani:  animation.export()
        })
    },
    deleteError(){
        let that = this;
        let animation = wx.createAnimation({
            duration: 50,
            timingFunction: 'ease',
        });
        animation.translateX(-25).step()
        this.setData({
            errorAni:  animation.export()
        })
        setTimeout(function(){
            animation = wx.createAnimation({
                duration: 50,
                timingFunction: 'ease',
            });
            animation.translateX(+25).step()
            that.setData({
                errorAni:  animation.export()
            });
            setTimeout(function(){
                animation = wx.createAnimation({
                    duration: 50,
                    timingFunction: 'ease',
                });
                animation.translateX(0).step()
                that.setData({
                    errorAni:  animation.export()
                });
            },50);
        },50);
        //按钮抖动
    },
    changePublish(e){
        if ( publish == false ) {
            publish = true;
        }
        else {
            publish = false;
        }
    },
    changeFixMode(){
        let that = this;
        if ( fixmode == false ) {
            fixmode = true;
        }
        else {
            if ( hasFixed == true ) {
                wx.showModal({
                    title: '即将回到预览模式',
                    content: '这将不会保存信息！',
                    cancelColor: '#6B7CA1',
                    confirmColor: 'red',
                    confirmText: '确定',
                    success(res){
                        if(res.confirm){
                            fixmode = false;
                            hasFixed = false;
                            that.setData({
                                fixmode: fixmode
                            })
                        }
                    }
                });
            }
            else {
                fixmode = false;
            }
        }
        this.setData({
            fixmode: fixmode
        })
    },
    getCommentText(e){
        commentText = e.detail.value;
    },
    publishComment(e){
        let that = this;
        let pureText = "";
        let textArr = commentText.split(" ")
        for ( let i in textArr ) {
            pureText += textArr[i];
        }
        if ( commentText.length > 0 && pureText.length >= 1 ) {
            hasFixed = false;
            wx.disableAlertBeforeUnload();
            openid = app.globalData.openid;
            let comment = {"openid":openid,"comment":commentText,"like":{},createTime:db.serverDate()};
            db.collection('diaryDB').doc(id).update({
                data: {
                    comment: db.command.push([comment])
                },
                success: function(res) {
                    commentText = "";
                    that.setData({
                        commentText: commentText
                    });
                    that.getComment();
                }
            });
            if ( this.data.replyTarget ) {
                let targetID = this.data.replyTarget;
                db.collection('messageDB').add({
                    data: {
                        type: "reply",
                        targetID: targetID,
                        where: id,
                        data: commentText,
                        createTime: db.serverDate()
                    }
                })
            } else {
                db.collection('messageDB').add({
                    data: {
                        type: "comment",
                        targetID: authorid,
                        where: id,
                        data: commentText,
                        createTime: db.serverDate()
                    }
                })
            } 
        }
        else {
            wx.showToast({
              title: '评论字数过少！',
              icon: "none",
              duration: 1000
            })
            this.deleteError();
        }
    },
    getNickName(data){
        let that = this;
        let checkList = [];
        for ( let i in data ) {
            checkList.push(data[i]["openid"]);
        }
        db.collection("infoDB").where({
            _openid: db.command.in(checkList)
        }).get({
            success: function(res) {
                let nicknameDict = {};
                for ( let i in res.data ) {
                    nicknameDict[res.data[i]._openid] = res.data[i].nickname;
                }
                for ( let i in commentList ) {
                    commentList[i]["nickname"] = nicknameDict[commentList[i]["openid"]]
                }
                that.setData({
                    commentList: commentList
                })
            }
        })
    },
    deleteComment(e){
        let that = this;
        let idx = this.data.commentIndex;
        let comment = commentList[idx]["comment"];
        let createTime = commentList[idx]["createTime"].valueOf();
        let timeMax = new Date(createTime+3000);
        let timeMin = new Date(createTime-3000);
        openid = app.globalData.openid;
        if ( openid == authorid || commentList[idx]["openid"] == openid ) {
            wx.showModal({
                title: '即将删除这条评论',
                content: '这可是精彩的发言哇！',
                cancelColor: '#6B7CA1',
                confirmColor: 'red',
                confirmText: '确定',
                success(res){
                    if(res.confirm){
                        commentList.splice(idx,1);
                        db.collection("diaryDB").doc(id).update({
                            data: {
                                comment: commentList
                            },
                            success: function(res) {
                                that.setData({
                                    commentList: commentList
                                })
                            }
                        })
                        db.collection("messageDB").where({
                            where: id,
                            type: "comment",
                            data: comment,
                            createTime: db.command.and(db.command.gte(timeMin),db.command.lte(timeMax))
                        }).remove();
                    }
                    that.cancelPickComment();
                }
            });
        }
    },
    likeItComment(e){
        let that = this;
        let index = e.currentTarget.dataset.index;
        let likeit = e.currentTarget.dataset.likeit;
        if ( likeit == false ) {
            commentList[index]["likeit"] = true;
            db.collection('diaryDB').doc(id).update({
                data: {
                    [`comment.${index}.like.${app.globalData.openid}`]: 1
                }
            });
            db.collection('messageDB').add({
                data: {
                    type: "likeComment",
                    targetID: commentList[index]["openid"],
                    where: id,
                    data: commentList[index]["comment"],
                    createTime: db.serverDate()
                }
            })
            commentList[index]["likeNumber"] += 1;
            that.setData({
                commentList
            })
        }
        else {
            commentList[index]["likeit"] = false;
            db.collection('diaryDB').doc(id).get({
                success: function(res) {
                    let like = res.data.comment[index].like;
                    delete like[app.globalData.openid];
                    db.collection('diaryDB').doc(id).update({
                        data: {
                            [`comment.${index}.like`]: db.command.set(like)
                        }
                    });
                }
            });
            db.collection('messageDB').where({
                type: "likeComment",
                targetID: commentList[index]["openid"],
                data: commentList[index]["comment"],
                where: id
            }).remove();
            commentList[index]["likeNumber"] -= 1;
            that.setData({
                commentList
            })
        }
    },
    pickComment(e){
        selectComment = e.currentTarget.dataset.comment;
        commentAuthorNickname = e.currentTarget.dataset.nickname;
        this.setData({
            selectComment: selectComment,
            commentAuthorNickname: commentAuthorNickname,
            isSelectComment: true,
            cancelAni: false,
            commentIndex: Number(e.currentTarget.dataset.index) 
        });
    },
    cancelPickComment(){
        let that = this;
        this.setData({
            cancelAni: true
        })
        setTimeout(function(){
            that.setData({
                isSelectComment: false,
            })
        },500)
    },
    copyComment(){
        let that = this;
        wx.setClipboardData({
            data: selectComment,
            success: function(res){
                wx.showToast({
                  title: '复制评论成功',
                  icon: "none"
                });
                that.setData({
                    isSelectComment: false
                });
            }
        })
    },
    likeItDiary(){
        let that = this;
        if ( likeit == false ) {
            likeit = true;
            db.collection('diaryDB').doc(id).update({
                data: {
                    [`like.${app.globalData.openid}`]: 1
                }
            });
            console.log(authorid+" "+id);
            db.collection('messageDB').add({
                data: {
                    type: "like",
                    targetID: authorid,
                    where: id,
                    createTime: db.serverDate()
                }
            });
            let likeNumber = this.data.likeNumber + 1;
            that.setData({
                likeit: likeit,
                likeNumber: likeNumber
            })
        }
        else {
            likeit = false;
            db.collection('diaryDB').doc(id).get({
                success: function(res) {
                    let like = res.data.like;
                    delete like[app.globalData.openid];
                    db.collection('diaryDB').doc(id).update({
                        data: {
                            like: db.command.set(like)
                        }
                    });
                }
            })
            console.log(authorid+" "+id);
            db.collection('messageDB').where({
                type: "likeComment",
                targetID: authorid,
                where: id
            }).remove();
            let likeNumber = this.data.likeNumber - 1;
            that.setData({
                likeit: likeit,
                likeNumber: likeNumber
            })
        }
    },
    favouriteItDiary(){
        let that = this;
        if ( favouriteit == false ) {
            favouriteit = true;
            db.collection('diaryDB').doc(id).update({
                data: {
                    [`favourite.${app.globalData.openid}`]: 1
                }
            });
            db.collection('infoDB').where({
                _openid: openid
            }).update({
                data: {
                    [`favourite.${id}`]: 1
                }
            }) 
            let favouriteNumber = this.data.favouriteNumber + 1;
            that.setData({
                favouriteit: favouriteit,
                favouriteNumber: favouriteNumber
            })
        }
        else {
            favouriteit = false;
            db.collection('diaryDB').doc(id).get({
                success: function(res) {
                    let favourite = res.data.favourite;
                    delete favourite[app.globalData.openid];
                    db.collection('diaryDB').doc(id).update({
                        data: {
                            favourite: db.command.set(favourite)
                        }
                    });
                }
            })
            db.collection('infoDB').where({
                _openid: app.globalData.openid
            }).get({
                success: function(res) {
                    let f = res.data[0].favourite;
                    delete f[id];
                    db.collection('infoDB').where({
                        _openid: app.globalData.openid
                    }).update({
                        data: {
                            favourite: db.command.set(f)
                        },
                    });
                }
            });
            let favouriteNumber = this.data.favouriteNumber - 1;
            that.setData({
                favouriteit: favouriteit,
                favouriteNumber: favouriteNumber
            })
        }
    },
    replyComment(e){
        let that = this;
        let idx = this.data.commentIndex;
        let comment = commentList[idx]["comment"];
        let replyPrefix = "回复" + (idx + 1) + "L(" + commentList[idx]["nickname"] + ")：";
        commentText = replyPrefix + commentText;
        this.setData({
            replyPrefix,
            commentText,
            replyTarget: commentList[idx]["openid"],
            isSelectComment: false})
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})